let DBConfig = require("../config/DBConfig_lcx");

module.exports = {
  async selectUserInfo(req, resp) {
    let userInfo = await new Promise((resolve, reject) => {
      DBConfig.db("select * from set_meal", [], (err, data) => {
        // console.log(111, data);
        if (data) {
          resolve(data);
        } else {
          reject(err);
        }
      });
    });

    resp.send(userInfo);
  },

  async deleteSet(req, resp) {
    // console.log(999, req);
    let { id } = req.body;

    let deleteSet = await new Promise((resolve, reject) => {
      DBConfig.db(
        "DELETE FROM set_meal WHERE productId = " + id + "",
        [],
        (err, data) => {
          // console.log(111, data);
          if (data) {
            resolve(data);
          } else {
            reject(err);
          }
        }
      );
    });

    resp.send(deleteSet);
  },

  //搜 测试 广州 美年大健康
  async searchSet(req, resp) {
    let { setsName, city, org } = req.body;
    // console.log("useruser", user);
    // console.log("searchValue", req.body);

    let searchSet = await new Promise((resolve, reject) => {
      // let sql =
      // "SELECT * FROM set_meal WHERE com_proName like '%" + searchValue + "%'";
      // console.log("sqlsql", sql);
      DBConfig.db(
        "SELECT * FROM set_meal WHERE com_proName like '%" +
          setsName +
          "%' and com_area like '%" +
          city +
          "%' and org_name like '%" +
          org +
          "%'",
        [],
        (err, data) => {
          console.log(999, data);
          if (data) {
            resolve(data);
          } else {
            reject(err);
          }
        }
      );
    });

    resp.send(searchSet);
  },

  async getCities(req, resp) {
    // let { searchValue } = req.body;
    // console.log("searchValue", searchValue);
    // console.log("searchValue", req.body);

    let getCities = await new Promise((resolve, reject) => {
      DBConfig.db("SELECT * FROM chinaCity", [], (err, data) => {
        if (data) {
          resolve(data);
        } else {
          reject(err);
        }
      });
    });

    resp.send(getCities);
  },

  async getAllOrganization(req, resp) {
    let { searchValue } = req.body;
    // console.log("searchValue", searchValue);
    // console.log("searchValue", req.body);

    let getAllOrganization = await new Promise((resolve, reject) => {
      DBConfig.db("SELECT * FROM organization", [], (err, data) => {
        if (data) {
          resolve(data);
        } else {
          reject(err);
        }
      });
    });

    resp.send(getAllOrganization);
  },

  async getAllSingleSet(req, resp) {
    let { searchValue } = req.body;
    // console.log("searchValue", searchValue);
    // console.log("searchValue", req.body);

    let getAllSingleSet = await new Promise((resolve, reject) => {
      DBConfig.db("SELECT * FROM physical", [], (err, data) => {
        if (data) {
          resolve(data);
        } else {
          reject(err);
        }
      });
    });

    resp.send(getAllSingleSet);
  },

  //搜 体检单项
  async searchSingleSet(req, resp) {
    let { setsName, city, org } = req.body;
    // console.log("useruser", user);
    // console.log("searchValue", req.body);
    let sql =
      "SELECT * FROM physical WHERE phy_projectName like '%" +
      setsName +
      "%' and area like '%" +
      city +
      "%' and org_name like '%" +
      org +
      "%'";

    // console.log("sql", sql);

    let searchSingleSet = await new Promise((resolve, reject) => {
      // let sql =
      // "SELECT * FROM set_meal WHERE com_proName like '%" + searchValue + "%'";
      // console.log("sqlsql", sql);
      DBConfig.db(
        "SELECT * FROM physical WHERE phy_projectName like '%" +
          setsName +
          "%' and area like '%" +
          city +
          "%' and org_name like '%" +
          org +
          "%'",
        [],
        (err, data) => {
          // console.log(999, data);
          if (data) {
            resolve(data);
          } else {
            reject(err);
          }
        }
      );
    });

    resp.send(searchSingleSet);
  },

  async deleteSingleSet(req, resp) {
    // console.log(999, req);
    let { id } = req.body;

    let deleteSingleSet = await new Promise((resolve, reject) => {
      DBConfig.db(
        "DELETE FROM physical WHERE phy_id = " + id + "",
        [],
        (err, data) => {
          // console.log(111, data);
          if (data) {
            resolve(data);
          } else {
            reject(err);
          }
        }
      );
    });

    resp.send(deleteSingleSet);
  },

  async switchStatus(req, resp) {
    // console.log(999, req);
    let { id, checked } = req.body;
    // console.log(id, checked);
    let sql =
      "UPDATE physical SET state='" + checked + "' WHERE phy_id='" + id + "'";
    // console.log("sqlsql", sql);

    let checkedStatus;
    checked == 1 ? (checkedStatus = 0) : (checkedStatus = 1);

    let switchStatus = await new Promise((resolve, reject) => {
      DBConfig.db(
        "UPDATE physical SET state='" +
          checkedStatus +
          "' WHERE phy_id='" +
          id +
          "'",
        [],
        (err, data) => {
          // console.log(111, data);
          if (data) {
            resolve(data);
          } else {
            reject(err);
          }
        }
      );
    });

    // resp.send(switchStatus);
    resp.json({ error: 0, data: switchStatus, msg: "modify success" });
  },

  async addSingleSet(req, resp) {
    // console.log(999, req);
    let {
      phy_projectName,
      phy_proId,
      phy_oldPrice,
      phy_salePrice,
      org_name,
      phy_suitTag,
      state,
      phy_suitRange,
      phy_checkMean,
      phy_notices,
      area,
    } = req.body;
    // console.log("req.bodyreq.body", req.body);
    // let sql =
    //   "UPDATE physical SET state='" + checked + "' WHERE phy_id='" + id + "'";
    // console.log("sqlsql", sql);

    let checkedStatus;
    state == true ? (checkedStatus = 1) : (checkedStatus = 0);

    let addSingleSet = await new Promise((resolve, reject) => {
      DBConfig.db(
        "INSERT INTO physical (phy_proId, phy_projectName, phy_oldPrice, phy_salePrice, area, state, phy_salesNum, phy_suitTag, phy_suitRange, phy_checkMean, org_name,phy_notices) VALUES (?,?,?,?,?,?,0,?, ?, ?, ?, ?)",
        [
          phy_proId,
          phy_projectName,
          phy_oldPrice,
          phy_salePrice,
          area,
          checkedStatus,
          phy_suitTag,
          phy_suitRange,
          phy_checkMean,
          org_name,
          phy_notices,
        ],
        (err, data) => {
          // console.log(111, data);
          if (data) {
            resolve(data);
          } else {
            reject(err);
          }
        }
      );
    });

    // resp.send(switchStatus);
    resp.json({ error: 0, data: addSingleSet, msg: "modify success" });
  },

  async editSingleSet(req, resp) {
    let {
      phy_proId,
      phy_projectName,
      phy_oldPrice,
      phy_salePrice,
      area,
      state,
      phy_suitTag,
      phy_suitRange,
      phy_checkMean,
      org_name,
      phy_notices,
      id,
    } = req.body;

    let checkedStatus;
    state == true ? (checkedStatus = 1) : (checkedStatus = 0);
    let editSingleSet = await new Promise((resolve, reject) => {
      DBConfig.db(
        "UPDATE physical SET phy_proId=?, phy_projectName=?, phy_oldPrice=?, phy_salePrice=?, area=?, state=?, phy_suitTag=?, phy_suitRange=?, phy_checkMean=?, org_name=?, phy_notices=? WHERE phy_id=?",
        [
          phy_proId,
          phy_projectName,
          phy_oldPrice,
          phy_salePrice,
          area,
          checkedStatus,
          phy_suitTag,
          phy_suitRange,
          phy_checkMean,
          org_name,
          phy_notices,
          id,
        ],
        (err, data) => {
          if (data) {
            resolve(data);
          } else {
            reject(err);
          }
        }
      );
    });

    resp.send(editSingleSet);
  },

  async getSingleSet(req, resp) {
    // console.log(999, req);
    let { id } = req.body;

    let getSingleSet = await new Promise((resolve, reject) => {
      DBConfig.db(
        "select * from set_meal WHERE productId = " + id + "",
        [],
        (err, data) => {
          // console.log(111, data);
          if (data) {
            resolve(data);
          } else {
            reject(err);
          }
        }
      );
    });

    resp.send(getSingleSet);
  },

  async deleteMoreSingleSet(req, resp) {
    console.log(req.body);
    let obj = req.body;
    let weneed = "";

    for (var i in obj) {
      weneed += obj[i] + ",";
    }
    let ans = weneed.substring(0, weneed.length - 1);

    let deleteMoreSingleSet = await new Promise((resolve, reject) => {
      DBConfig.db(
        "DELETE FROM physical WHERE phy_id in (?)",
        [ans],
        (err, data) => {
          // console.log(111, data);
          if (data) {
            resolve(data);
          } else {
            reject(err);
          }
        }
      );
    });

    resp.send(deleteMoreSingleSet);
  },

  async addSet(req, resp) {
    console.log(11111, req.body);

    // const {
    //   com_proName,
    //   com_UID,
    //   com_originalPrice,
    //   com_presentPrice,
    //   com_address,
    //   com_label,
    //   org_name,
    //   com_status,
    //   com_introduce,
    //   com_rules,
    //   startTimeName,
    //   endTimeName,
    // } = req.body;

    let addSet = await new Promise((resolve, reject) => {
      // DBConfig.db(
      //   // "DELETE FROM physical WHERE phy_id in (?)",
      //   [],
      //   (err, data) => {
      //     // console.log(111, data);
      //     if (data) {
      //       resolve(data);
      //     } else {
      //       reject(err);
      //     }
      //   }
      // );
    });

    resp.send(addSet);
  },

  //搜机构
  async searchSingleOri(req, resp) {
    console.log(555, req.body);
    let { org_name, city, org_type } = req.body;

    let searchSingleOri = await new Promise((resolve, reject) => {
      DBConfig.db(
        "SELECT * FROM organization WHERE org_name like '%" +
          org_name +
          "%' and city like '%" +
          city +
          "%' and org_type like '%" +
          org_type +
          "%'",
        [],
        (err, data) => {
          // console.log(999, data);
          if (data) {
            resolve(data);
          } else {
            reject(err);
          }
        }
      );
    });

    resp.send(searchSingleOri);
  },

  async deleteOri(req, resp) {
    // console.log(999, req);
    let { org_id } = req.body;

    let deleteOri = await new Promise((resolve, reject) => {
      DBConfig.db(
        "DELETE FROM organization WHERE org_id = " + org_id + "",
        [],
        (err, data) => {
          // console.log(111, data);
          if (data) {
            resolve(data);
          } else {
            reject(err);
          }
        }
      );
    });

    resp.send(deleteOri);
  },

  async deleteMoreOri(req, resp) {
    console.log(req.body);
    let obj = req.body;
    let weneed = "";

    for (var i in obj) {
      weneed += obj[i] + ",";
    }
    let ans = weneed.substring(0, weneed.length - 1);

    let deleteMoreOri = await new Promise((resolve, reject) => {
      DBConfig.db(
        "DELETE FROM organization WHERE org_id in (?)",
        [ans],
        (err, data) => {
          // console.log(111, data);
          if (data) {
            resolve(data);
          } else {
            reject(err);
          }
        }
      );
    });

    resp.send(deleteMoreOri);
  },

  //用户注册
  async addUser(req, resp) {
    let { userName, userPassword, userTel } = req.body;

    let addUser = await new Promise((resolve, reject) => {
      DBConfig.db(
        "INSERT INTO users (userName, userPassword, userTel) VALUES ( ?, ?, ?)",
        [userName, userPassword, userTel],
        (err, data) => {
          console.log(999, data);
          if (data) {
            // resolve(data);
            resp.json({ error: 0, data: data, msg: "添加用户成功" });
          } else {
            // reject(err);
            resp.json({ error: 1, data: err, msg: "用户添加失败" });
          }
        }
      );
    });

    resp.send(addUser);
  },

  //用户登入
  async searchUser(req, resp) {
    console.log(444, req.body);
    let { userName, userPassword, userTel } = req.body;
    console.log(222, userName, userPassword);

    let searchUser = await new Promise((resolve, reject) => {
      DBConfig.db(
        "select * from users where userName = ? and userPassword = ? and userTel = ?",
        [userName, userPassword, userTel],
        (err, data) => {
          // console.log(999, data);
          if (data.length > 0) {
            // resolve(data);
            resp.json({ error: 0, data: data, msg: "查询成功" });
          } else {
            // reject(err);
            resp.json({ error: 1, data: err, msg: "用户不存在" });
          }
        }
      );
    });
  },

  //用户查询
  async searchUserById(req, resp) {
    let { userId } = req.body;

    let searchUserById = await new Promise((resolve, reject) => {
      DBConfig.db(
        "select * from users where userId = ? ",
        [userId],
        (err, data) => {
          // console.log(999, data);
          if (data.length > 0) {
            // resolve(data);
            resp.json({ error: 0, data: data, msg: "查询成功" });
          } else {
            // reject(err);
            resp.json({ error: 1, data: err, msg: "用户不存在" });
          }
        }
      );
    });
  },

  //收藏查询，根据用户id查询
  async getCollections(req, resp) {
    let { userId } = req.body;

    let sql1 = "SELECT setsId FROM collect where userId=" + userId + "";
    let sql2 = "SELECT organizationId FROM collect where userId=" + userId + "";
    let setsData = [];
    let orgsData = [];
    let userSets = [];
    let userOrgs = [];
    let allCollect = [];
    // allCollect.push(userSets, userOrgs);

    setsData = await new Promise((resolve, reject) => {
      DBConfig.db(sql1, [], (err, data) => {
        // console.log(999, data);
        if (data) {
          resolve(data);
        } else {
          reject(err);
        }
      });
    });

    orgsData = await new Promise((resolve, reject) => {
      DBConfig.db(sql2, [], (err, data) => {
        // console.log(999, data);
        if (data) {
          resolve(data);
        } else {
          reject(err);
        }
      });
    });

    userOrgs = await new Promise((resolve, reject) => {
      DBConfig.db(
        "SELECT * FROM organization where org_id in (" +
          orgsData[0].organizationId +
          ")",
        [],
        (err, data) => {
          // console.log(999, data);
          if (data) {
            resolve(data);
            allCollect.push(data);
          } else {
            reject(err);
          }
        }
      );
    });

    userSets = await new Promise((resolve, reject) => {
      DBConfig.db(
        "SELECT * FROM set_meal where productId in (" +
          setsData[0].setsId +
          ")",
        [],
        (err, data) => {
          // console.log(999, data);
          if (data) {
            resolve(data);
            allCollect.push(data);
          } else {
            reject(err);
          }
        }
      );
    });

    console.log(4444, userSets, userOrgs);
    console.log(5555, allCollect);

    // let getCollections = await new Promise((resolve, reject) => {
    //   DBConfig.db(
    //     "SELECT * FROM set_meal where productId in (" +
    //       setsData[0].setsId +
    //       ")",
    //     [],
    //     (err, data) => {
    //       // console.log(999, data);
    //       if (data) {
    //         // resolve(data);
    //         resp.json({ error: 0, data: data, msg: "查询成功" });
    //       } else {
    //         // reject(err);
    //         resp.json({ error: 1, data: err, msg: "用户不存在" });
    //       }
    //     }
    //   );
    // });

    // let getCollections = allCollect;
    resp.json({ error: 0, data: allCollect, msg: "查询成功" });
  },

  //收藏添加
  async addCollection(req, resp) {
    // let { organizationId, setsId, userId } = req.body;

    let organizationId = 2;
    // let setsId = 42;

    let sql1 = "SELECT setsId FROM collect where userId=2";
    let sql2 = "SELECT organizationId FROM collect where userId=2";

    let setsData = [];
    let orgsData = [];

    let newSetsData = [];

    //UPDATE `onlineappointment`.`collect` SET `organizationId`='2' WHERE `collect_Id`='3';

    setsData = await new Promise((resolve, reject) => {
      DBConfig.db(sql1, [], (err, data) => {
        // console.log(999, data);
        if (data) {
          resolve(data);
        } else {
          reject(err);
        }
      });
    });

    orgsData = await new Promise((resolve, reject) => {
      DBConfig.db(sql2, [], (err, data) => {
        // console.log(999, data);
        if (data) {
          resolve(data);
        } else {
          reject(err);
        }
      });
    });

    console.log(4444, setsData);

    if (organizationId) {
      let setsTest = await new Promise((resolve, reject) => {
        DBConfig.db(
          "SELECT * FROM set_meal where productId in (" +
            setsData[0].setsId +
            ")",
          [],
          (err, data) => {
            // console.log(999, data);
            if (data) {
              resolve(data);
              newSetsData.push(...data, organizationId);
            } else {
              reject(err);
            }
          }
        );
      });
    }

    if (setsId) {
    }

    // let addCollection = await new Promise((resolve, reject) => {
    //   DBConfig.db(
    //     "select * from users where userId = ? ",
    //     [userId],
    //     (err, data) => {
    //       // console.log(999, data);
    //       if (data.length > 0) {
    //         // resolve(data);
    //         resp.json({ error: 0, data: data, msg: "查询成功" });
    //       } else {
    //         // reject(err);
    //         resp.json({ error: 1, data: err, msg: "用户不存在" });
    //       }
    //     }
    //   );
    // });
    resp.json({ error: 0, data: setsTest, msg: "添加成功" });
  },

  async orgSwitchStatus(req, resp) {
    // console.log(999, req);
    let { id, checked } = req.body;

    let checkedStatus;
    checked == 1 ? (checkedStatus = 0) : (checkedStatus = 1);

    let orgSwitchStatus = await new Promise((resolve, reject) => {
      DBConfig.db(
        "UPDATE organization SET state='" +
          checkedStatus +
          "' WHERE org_id='" +
          id +
          "'",
        [],
        (err, data) => {
          // console.log(111, data);
          if (data) {
            // resolve(data);
            resp.json({
              error: 0,
              data: data,
              msg: "modify success",
            });
          } else {
            // reject(err);
            resp.json({
              error: 1,
              data: err,
              msg: "modify fail",
            });
          }
        }
      );
    });

    // resp.send(switchStatus);
    // resp.json({ error: 0, data: orgSwitchStatus, msg: "modify success" });
  },
};
